package com.vp.org.web.servlet;

import com.vp.org.dao.BookInfoDao;
import com.vp.org.dao.impl.BookInfoDaoImpl;
import com.vp.org.pojo.*;
import com.vp.org.service.BookService;
import com.vp.org.service.OrderService;
import com.vp.org.service.impl.BookServiceImpl;
import com.vp.org.service.impl.OrderServiceImpl;
import com.vp.org.util.UUIDUtil;
import com.vp.org.web.base.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@SuppressWarnings({"unused", "RedundantThrows"})
@WebServlet(name = "book", value = "/book")
public class BookServlet extends BaseServlet {

    private static List<Map<String, String>> cart = new ArrayList<>();

    private BookService bookService = new BookServiceImpl();

    private OrderService orderService = new OrderServiceImpl();

    // 郭淑华 写
    private BookInfo bookInfo = null;
    private BookInfoDao bookInfoDao = null;
    private AdminInfo adminInfo = null;

    @SuppressWarnings("FieldCanBeLocal")
    private Map<String, String> car;

    public String query(HttpServletRequest req, HttpServletResponse resp) {
        int id = Integer.parseInt(req.getParameter("id"));

        BookInfo book = bookService.findById(id);

        String str = req.getContextPath() + "user/";

        if (book != null) {
            // 如果书查到了 就查它的所有评论
            req.getSession().setAttribute("remarks", bookService.findForRemark(id));
            req.getSession().setAttribute("book", book);

            return "r:" + str + "details.jsp";
        } else {
            return "r:" + str + "index.jsp";
        }
    }

    public String name(HttpServletRequest req, HttpServletResponse resp) {
        String search = req.getParameter("search");

        BookInfo book = bookService.findByName(search);

        String str = req.getContextPath() + "user/";

        if (book != null) {
            // 如果书查到了 就查它的所有评论
            req.getSession().setAttribute("remarks", bookService.findForRemark(book.getId()));
            req.getSession().setAttribute("book", book);

            return "r:" + str + "details.jsp";
        } else {
            return "r:" + str + "index.jsp?search=0";
        }
    }

    public String cart(HttpServletRequest req, HttpServletResponse resp) {

        car = new HashMap<>();

        car.put("userId", req.getParameter("userId"));
        car.put("bookId", req.getParameter("bookId"));
        car.put("bookCount", req.getParameter("bookCount"));
        car.put("bookName", req.getParameter("bookName"));
        car.put("bookPrice", req.getParameter("bookPrice"));
        car.put("bookImg", req.getParameter("bookImg"));

        cart.add(car);

        String str = req.getContextPath() + "user/";

        req.getSession().setAttribute("cart", cart);

        return "r:" + str + "details.jsp?ok=1";
    }

    public String balance(HttpServletRequest req, HttpServletResponse resp) {

        String[] seles = req.getParameter("seles").split("-");

        Orders orders;

        boolean is = false;

        for (String sele : seles) {
            if (!"".equals(sele)) {
                orders = new Orders();
                int i = Integer.parseInt(sele);
                car = cart.get(i);
                orders.setOrderNum(UUIDUtil.getUUID());
                orders.setUserId(Integer.parseInt(car.get("userId")));
                orders.setOrderName("此订单非彼订单");
                orders.setGoodsName(car.get("bookName"));
                orders.setStatus("0");
                orders.setPhone("17683706521");
                orders.setCount(Integer.parseInt(car.get("bookCount")));
                orders.setPrice(Double.parseDouble(car.get("bookPrice")));

                is = orderService.addOrders(orders) > 0;
            }
        }

        // 生成订单后就清空购物车
        cart.clear();

        String str = req.getContextPath() + "user/";

        if (is)
        return "r:" + str + "buy.jsp?ok=1";
        else return "r:" + str + "buy.jsp?ok=0";
    }

    public String collect(HttpServletRequest req, HttpServletResponse resp) {
        int booKId = Integer.parseInt(req.getParameter("bookId"));
        int userId = Integer.parseInt(req.getParameter("userId"));

        bookService.collectBook(booKId, userId);

        String str = req.getContextPath() + "user/";

        return "r:" + str + "buy.jsp?collect=1";
    }

    public String collectQ(HttpServletRequest req, HttpServletResponse resp) {

        List<BookInfo> collects = new ArrayList<>();
        UserInfo user = (UserInfo) req.getSession().getAttribute("user");
        int i = 0;

        // 先查此用户全部收藏的书籍， 在通过书籍id查书籍详细信息
        for (Collect collect : bookService.queryAll(user.getUserId())) {
            collects.add(bookService.findById(Integer.parseInt(collect.getBookId())));
            collects.get(i).setIsbn(collect.getId() + "");
            i++;
        }

        req.getSession().setAttribute("collects", collects);

        String str = req.getContextPath() + "user/center/";

        return "r:" + str + "user_2.jsp?page=1";
    }

    public String collectD(HttpServletRequest req, HttpServletResponse resp) {

        bookService.delete(Integer.parseInt(req.getParameter("id")));

        String str = req.getContextPath() + "user/center/";

        return "r:" + str + "user_2.jsp?page=1&msg=1";
    }

    // 郭淑华 写
    public void addBookInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        adminInfo = new AdminInfo();
        bookInfo = new BookInfo();
        bookInfoDao = new BookInfoDaoImpl();

        // 用BeanUtils封装
        try {
            BeanUtils.populate(bookInfo, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        adminInfo.setAdmin("admin");
        if (bookInfoDao.adminAddBook(bookInfo,adminInfo) > 0) {
            // 添加成功
            request.setAttribute("addBook",1);
            request.getRequestDispatcher("/admin/bookAdd.jsp").forward(request,response);
            // 地址重定向
            //response.sendRedirect("/admin/bookAdd.jsp");

        } else {
            // 添加失败
            response.sendRedirect("/admin/error.jsp");
        }
    }

    public void deleteBookInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        bookInfo = new BookInfo();
        bookInfoDao = new BookInfoDaoImpl();
        adminInfo = new AdminInfo();

        String id = request.getParameter("id");
        String admin = request.getParameter("admin");

        bookInfo.setId(Integer.parseInt(id));
        adminInfo.setAdmin(admin);

        if (bookInfoDao.adminDeleteBook(bookInfo,adminInfo) > 0) {
            // 删除成功
            // 地址重定向http://localhost:8080//book?method=findByPage&pageIndex=1
            //response.sendRedirect("http://localhost:8080/admin/queryBook.jsp");
            response.sendRedirect("http://localhost:8080/book?method=findByPage&pageIndex=1");
        } else {
            // 删除失败
            response.sendRedirect("/admin/error.jsp");
        }
    }

    public void updateBookInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        bookInfo = new BookInfo();
        bookInfoDao = new BookInfoDaoImpl();
        adminInfo = new AdminInfo();

        // 用BeanUtils封装
        try {
            BeanUtils.populate(bookInfo, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }


        if (bookInfoDao.adminUpdateBook(bookInfo) > 0) {
            // 修改成功

            /*request.setAttribute("updateBook",1);
            request.getRequestDispatcher("/admin/bookQuery.jsp").forward(request,response);*/
            // 地址重定向
            response.sendRedirect("/admin/bookQuery.jsp");

        } else {
            // 修改失败
            response.sendRedirect("/admin/error.jsp");
        }
    }

    public void findByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收用户点击的上一页，下一页或者是指定的页数
        int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));

        bookInfoDao = new BookInfoDaoImpl();

        // 分页查询（默认第一页）
        request.getSession().setAttribute("bookInfos",bookInfoDao.adminBookPagingQuery(pageIndex,7));

        // 总页数
        request.getSession().setAttribute("bookPage",bookInfoDao.adminQueryBookPage());

        //存储当前这一页是第几页
        request.getSession().setAttribute("currentPage",pageIndex);

        // 地址重定向
        response.sendRedirect("admin/bookQuery.jsp");

    }

    public void findByPagePromotion(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收用户点击的上一页，下一页或者是指定的页数
        int pageIndex4 = Integer.parseInt(request.getParameter("pageIndex4"));

        bookInfoDao = new BookInfoDaoImpl();

        // 分页查询（默认第一页）
        request.getSession().setAttribute("promotions",bookInfoDao.promotionBooks(pageIndex4));

        // 总页数
        request.getSession().setAttribute("promotionPage",bookInfoDao.promotionPage());

        //存储当前这一页是第几页
        request.getSession().setAttribute("currentPage4",pageIndex4);

        // 地址重定向
        response.sendRedirect("admin/bookPromotionQuery.jsp");

    }

    public void addPromotion(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        bookInfo = new BookInfo();
        bookInfoDao = new BookInfoDaoImpl();
        adminInfo = new AdminInfo();

        // 用BeanUtils封装
        try {
            BeanUtils.populate(bookInfo, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        adminInfo.setAdmin("admin");
        if (bookInfoDao.adminAddBook(bookInfo,adminInfo) > 0) {
            // 添加成功
            request.setAttribute("addBook",1);
            request.getRequestDispatcher("/admin/bookPromotionAdd.jsp").forward(request,response);
            // 地址重定向
            //response.sendRedirect("/admin/bookAdd.jsp");

        } else {
            // 添加失败
            response.sendRedirect("/admin/error.jsp");
        }
    }

    public void deletePromotion(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        adminInfo = new AdminInfo();
        bookInfo = new BookInfo();
        bookInfoDao = new BookInfoDaoImpl();

        String id = request.getParameter("id");
        String admin = request.getParameter("admin");

        bookInfo.setId(Integer.parseInt(id));
        adminInfo.setAdmin(admin);

        if (bookInfoDao.adminDeleteBook(bookInfo,adminInfo) > 0) {
            // 删除成功
            // 地址重定向http://localhost:8080//book?method=findByPage&pageIndex=1
            //response.sendRedirect("http://localhost:8080/admin/queryBook.jsp");
            response.sendRedirect("http://localhost:8080/book?method=findByPagePromotion&pageIndex4=1");
        } else {
            // 删除失败
            response.sendRedirect("/admin/error.jsp");
        }
    }

    public void updatePromotion(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        bookInfo = new BookInfo();
        bookInfoDao = new BookInfoDaoImpl();
        adminInfo = new AdminInfo();

        // 用BeanUtils封装
        try {
            BeanUtils.populate(bookInfo, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        if (bookInfoDao.adminUpdateBook(bookInfo) > 0) {
            // 修改成功

            request.setAttribute("updateBook",1);
            request.getRequestDispatcher("/admin/bookPromotionQuery.jsp").forward(request,response);

        } else {
            // 修改失败
            response.sendRedirect("/admin/error.jsp");
        }
    }
}
